#include "string.h"
#include <cctype>
#include <algorithm>

// 去除字符串首尾的空白字符
std::string StringUtils::trim(const std::string &str)
{
    if (str.empty())
        return str;

    size_t start = 0;
    size_t end = str.length() - 1;

    // 找到第一个非空白字符
    while (start <= end && std::isspace(static_cast<unsigned char>(str[start])))
    {
        start++;
    }

    // 找到最后一个非空白字符
    while (end >= start && std::isspace(static_cast<unsigned char>(str[end])))
    {
        end--;
    }

    if (start > end)
        return "";
    return str.substr(start, end - start + 1);
}

// 将字符串转换为小写
std::string StringUtils::toLower(const std::string &str)
{
    std::string result = str;
    std::transform(result.begin(), result.end(), result.begin(),
                   [](unsigned char c)
                   { return std::tolower(c); });
    return result;
}

// 将字符串转换为大写
std::string StringUtils::toUpper(const std::string &str)
{
    std::string result = str;
    std::transform(result.begin(), result.end(), result.begin(),
                   [](unsigned char c)
                   { return std::toupper(c); });
    return result;
}

// 分割字符串
std::vector<std::string> StringUtils::split(const std::string &str, char delimiter)
{
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(str);

    while (std::getline(tokenStream, token, delimiter))
    {
        tokens.push_back(token);
    }

    return tokens;
}

// 检查字符串是否以指定前缀开头
bool StringUtils::startsWith(const std::string &str, const std::string &prefix)
{
    if (str.length() < prefix.length())
        return false;
    return str.substr(0, prefix.length()) == prefix;
}

// 检查字符串是否以指定后缀结尾
bool StringUtils::endsWith(const std::string &str, const std::string &suffix)
{
    if (str.length() < suffix.length())
        return false;
    return str.substr(str.length() - suffix.length()) == suffix;
}

// 检查字符串是否包含指定子字符串
bool StringUtils::contains(const std::string &str, const std::string &substr)
{
    return str.find(substr) != std::string::npos;
}
